package cn.range.service;


import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import cn.range.utils.FormFile;
import cn.range.utils.SocketHttpRequester;


public class FileService {

	/**
	 * Save data.
	 * @param title
	 * @param timeLength
	 * @return
	 */
	/*public static boolean save(String title, String timeLength) {
		String path = "http://10.4.242.249:8080/webweb/ManageServlet";
		Map<String, String> params = new HashMap<String, String>();//Parameters are often saved in Map<>.
		params.put("title", title);
		params.put("timeLength", timeLength);
		//Post-method is always used to transfer data over 2Kb.
		//Data smaller than 2Kb, get/post is used.
		try {
			return sendGETRequest(path, params);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}*/

	/**
	 * Send GET request
	 * @param path
	 * @param params
	 * @return
	 * @throws Exception
	 */
	//Get
	private static boolean sendGETRequest(String path,
			Map<String, String> params) throws Exception{
		StringBuilder url = new StringBuilder();
		url.append("?");
		for(Map.Entry<String, String> entry : params.entrySet())
		{
			url.append(entry.getKey()).append("=");
			url.append(entry.getValue());
			url.append("&");
		}
		url.deleteCharAt(url.length()-1);//Just for deleting a "&" in the end of URL.
		HttpURLConnection con = (HttpURLConnection)new URL(url.toString()).openConnection();
		con.setConnectTimeout(5000);
		con.setRequestMethod("GET");
		if(con.getResponseCode() == 200)
		{
			return true;
		}
		return false;
	}

	public static boolean save(String fileName, File uploadFile) {
		String path = "http://10.4.240.1:8080/webweb/ManageServlet";
		Map<String, String> params = new HashMap<String, String>();//Parameters are often saved in Map<>.
		params.put("fileName", fileName);
		//params.put("timeLength", timeLength);
		
		FormFile formFile = new FormFile(fileName, uploadFile, "file", "text/xml");
		
		try{
			return SocketHttpRequester.post(path, params, formFile);
		}catch (Exception e){
			e.printStackTrace();
		}
		
		return false;
	}

	

}
